package com.roc.web.action.merinfo;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
  


import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblMchtInf;
import com.roc.service.ServiceException;
import com.roc.service.merinfo.MerinfoManageService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;

/**
 * 商户管理
 * @ClassName: merinfoManageAction
 * @Description: TODO
 * @author jdd
 * @date 2017年2月20日
 *
 */
@Component
@Namespace("/manage")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)

public class merinfoManageAction extends PaginationBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Logger logger = LogManager.getLogger(merinfoManageAction.class);

	private MerinfoManageSearchCondition searchCondition;
	private String merInfoIdList;
	@Autowired
	IPageService pageService1;
	
	@Autowired
	MerinfoManageService merinfoManageService;
	
	
	@Action(value="merinfoManage",results={@Result(name=SUCCESS,location="/pages/merinfo/merinfoManage.jsp")})
	public String merinfoManage(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		
		return SUCCESS;
		}
	/**
	 * 商户管理查询
	 * @Title: queryMerinfo
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 * @author jdd
	 */
	@Action(value="queryMerinfoManage",results={@Result(name=SUCCESS,location="/pages/merinfo/merinfoManage.jsp"),
			@Result(name = ERROR, location = "/error.jsp")})
	public String queryMerinfo(){
		 Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		 if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
         try {
        	 if(searchCondition==null){
        		 searchCondition=(MerinfoManageSearchCondition)getSearchConditionFromSession();
					if(searchCondition==null){
						searchCondition=new MerinfoManageSearchCondition();
					}
			}
					
			if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || 
			    op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())  ){
				searchCondition.setOpId(String.valueOf(op.getId()));//操作员id
				queryMerinfoList();
					}
         }catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
		
	}
	/**
	 * 查询方法
	 * @Title: queryMerinfoList
	 * @Description: TODO
	 * @param @throws Exception    
	 * @return void    
	 * @throws
	 * @author jdd
	 */
	 public void  queryMerinfoList() throws Exception{
			try {
				int rows=pageService1.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pageService1.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				List<TblMchtInf> msList = new ArrayList<TblMchtInf>();	
				if(searchRsList.size()>0 && searchRsList!=null){			
					Iterator iterator=searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj= (Object[])iterator.next();
						TblMchtInf msb = new TblMchtInf();
						msb.setId(Constance.Null2EmptyTrim(obj[0]));  //商户号
						msb.setNameBusi(Constance.Null2EmptyTrim(obj[1])); //商户简称
						msb.setName(Constance.Null2EmptyTrim(obj[2]));//商户注册名称
						msb.setIsGroup(Constance.Null2EmptyTrim(obj[3]));//商户等级    
						msb.setGroupCD(Constance.Null2EmptyTrim(obj[4]));//直连，间连
						//msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));//机构名称
						msb.setContactName(Constance.Null2EmptyTrim(obj[5])); //商户联系人
					    msb.setContactPhoneNo(Constance.Null2EmptyTrim(obj[6]));//手机号
						msb.setCertif(Constance.Null2EmptyTrim(obj[7])); //法人
						msb.setCertifNo(Constance.Null2EmptyTrim(obj[8]));//证件号
						msb.setBusiLiceNo(Constance.Null2EmptyTrim(obj[9]));//营业执照
						msb.setRegAddr(Constance.Null2EmptyTrim(obj[10])); //地址
						msb.setStatus(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[11])));//状态
						msList.add(msb);
					}
				}
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(SEARCH_RS_LIST, msList);
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
				
			} catch (ServiceException e) {
				
				logger.error(e.getMessage(),e);
				addActionError(e.getMessage());
				
			}
		}
	 /**
	  *  变更商户等级
	  * @Title: merinfoAlloat
	  * @Description: TODO
	  * @param @return    
	  * @return String    
	  * @throws
	  * @author jdd
	  */
		@Action(value="merinfoGrade")
		public String merinfoGrade(){
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			String name = searchCondition.getGrade();
		
			
			PrintWriter pw = null;
			JSONObject json = new JSONObject();
			try {
				getResponse().setCharacterEncoding("utf-8");
				pw = getResponse().getWriter();
				
				logger.info(op.getRealName()+"开始变更商户,商户号是："+merInfoIdList);
			Map<String,Object> resultMap = merinfoManageService.merinfoChangeGrade(searchCondition,op,merInfoIdList);
				json.put("rsList", merInfoIdList);
				json.put("msg", "变更成功");
				pw.write(json.toString());			
			} catch (Exception e) {
				logger.error("商户变更等级异常");
				logger.error(e.getMessage(),e);
			}finally{
				if(pw != null){
					pw.close();
				}
			}		
			return null;
		}
		/**
		 * 变更商户关联关系
		 * @Title: merinfoAssociation
		 * @Description: TODO
		 * @param @return    
		 * @return String    
		 * @throws
		 * @author jdd
		 */
		@Action(value="merinfoAssociation")
		public String merinfoAssociation(){
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			String name = searchCondition.getAssociation();
		
			
			PrintWriter pw = null;
			JSONObject json = new JSONObject();
			try {
				getResponse().setCharacterEncoding("utf-8");
				pw = getResponse().getWriter();
				
				logger.info(op.getRealName()+"开始变更商户关联关系,商户号是："+merInfoIdList);
			    Map<String,Object> resultMap = merinfoManageService.merinfoChangeAssociation(searchCondition,op,merInfoIdList);
			    json.put("rsList", merInfoIdList);
			    json.put("msg", "变更成功");
				pw.write(json.toString());			
			} catch (Exception e) {
				logger.error("商户变更关联关系异常");
				logger.error(e.getMessage(),e);
			}finally{
				if(pw != null){
					pw.close();
				}
			}		
			return null;
		}
	 
	 
	public MerinfoManageSearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(MerinfoManageSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	
	public String getMerInfoIdList() {
		return merInfoIdList;
	}
	public void setMerInfoIdList(String merInfoIdList) {
		this.merInfoIdList = merInfoIdList;
	}
	
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_MERINFO_MANAGE, searchCondition);
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_MERINFO_MANAGE);
	}
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
	 
	
	





}
